<template>
  <div class="exam-initiateexam-page">
    <nav-bar :title="title" theme="blue" message></nav-bar>
    <div class="page-main" style="margin-top: 44px">
      <div class="exam-initiateexam">
        <div class="exam-initiateexam-box" v-show="curPage === 'question'">
          <van-swipe
            ref="swipe"
            :loop="false"
            :stop-propagation="false"
            :show-indicators="false"
            @change="handleSwipeChange"
          >
            <van-swipe-item v-for="(item, index) in questionList" :key="index">
              <div class="exam-initiateexam-box-swipename">
                <p class="exam-initiateexam-box-swipename-left">
                  {{ typeData.number[index] }}{{ typeData.title[item.typeCode] }}
                  <span>（本题{{ item.score }}分）</span>
                </p>
                <p class="exam-initiateexam-box-swipename-right">
                  <span>{{ index + 1 }}</span>
                  /
                  {{ questionParams.total }}
                </p>
              </div>
              <div class="exam-initiateexam-box-content">
                <div class="exam-initiateexam-box-content-title">{{ item.orderNum + '、' }}{{ item.title }}</div>
                <template v-if="item.typeCode === '1'">
                  <div
                    v-for="(optionItem, optionIndex) in item.option"
                    :key="optionIndex"
                    class="exam-initiateexam-box-content-option"
                    @click.stop="item.answer = optionItem.itemName"
                  >
                    <p class="title-num" :class="item.answer === optionItem.itemName ? 'checked' : ''">
                      {{ optionItem.itemName }}
                    </p>
                    <p class="title-text">{{ optionItem.item }}</p>
                  </div>
                </template>
                <template v-if="item.typeCode === '2'">
                  <div
                    v-for="(optionItem, optionIndex) in item.option"
                    :key="optionIndex"
                    class="exam-initiateexam-box-content-option"
                    @click.stop="multipleChoose(item, optionItem)"
                  >
                    <p class="title-num" :class="item.answer.indexOf(optionItem.itemName) !== -1 ? 'checked' : ''">
                      {{ optionItem.itemName }}
                    </p>
                    <p class="title-text">{{ optionItem.item }}</p>
                  </div>
                </template>
                <template v-if="item.typeCode === '3'">
                  <van-field
                    v-model="item.answer"
                    placeholder="请输入答案"
                    rows="5"
                    autosize
                    type="textarea"
                    show-word-limit
                    :border="false"
                    class="van-field__value--textarea"
                    maxlength="500"
                  />
                </template>
              </div>
            </van-swipe-item>
          </van-swipe>
        </div>
        <div class="exam-answer-sheet" v-show="curPage === 'answerSheet'">
          <div style="overflow: hidden" v-for="(order, orderKey, orderIndex) in typeData.number" :key="orderKey">
            <div class="exam-answer-sheet-topic">
              <span class="exam-answer-sheet-topic-span"></span>
              {{ order }}{{ typeData.title[questionList[orderKey].typeCode] }}
            </div>
            <template v-for="(item, index) in questionList">
              <div
                class="exam-answer-sheet-option"
                :key="index"
                v-if="
                  (typeData.numberKeys[orderIndex - 1] === undefined && index < typeData.numberKeys[orderIndex + 1]) ||
                  (typeData.numberKeys[orderIndex + 1] === undefined && index >= typeData.numberKeys[orderIndex]) ||
                  (index < typeData.numberKeys[orderIndex + 1] && index > typeData.numberKeys[orderIndex - 1])
                "
                @click="handleAnswerSheetClick(index)"
              >
                <div class="exam-answer-sheet-option-title" :class="item.answer ? 'checked' : ''">
                  {{ item.orderNum }}
                </div>
              </div>
            </template>
          </div>
        </div>
      </div>
      <div class="answer-sheet">
        <div class="answer-sheet-answer">
          <van-tag type="primary" @click="curPage = curPage === 'question' ? 'answerSheet' : 'question'">
            {{ curPage === 'question' ? '答题卡' : '继续做题' }}
          </van-tag>
        </div>
        <div class="answer-sheet-time">
          <van-count-down :time="durationTime" @finish="onFinish" />
        </div>
        <div class="answer-sheet-submit"><van-tag type="primary" @click="onSubmit">提交试卷</van-tag></div>
      </div>
    </div>
  </div>
</template>
<script>
import LearnTest from '@/api/learnTest'
import { formatTimes } from '@/libs/tool'
export default {
  name: 'learnTest-exam-start',
  data() {
    return {
      title: '',
      curPage: 'question',
      durationTime: 3600000,
      questionParams: {
        examCode: this.$route.query.code,
        pageNumber: 1,
        recordSize: 0,
        pageSize: 999,
        total: 0
      },
      questionList: [],
      typeData: {
        numberOptions: ['一、', '二、', '三、'],
        numberKeys: [],
        number: {},
        title: {
          1: '单选题',
          2: '多选题',
          3: '问答题'
        }
      },
      answerParams: []
    }
  },
  computed: {
    clacType() {
      return function (item, key) {
        return !!(!key || (this.questionList[key - 1] && this.questionList[key - 1].typeCode !== item.typeCode))
      }
    }
  },
  mounted() {
    this.getQuestionList()
  },
  methods: {
    // 获取题目
    getQuestionList() {
      this.questionParams.recordSize = this.questionParams.pageSize * (this.questionParams.pageNumber - 1)
      LearnTest.Exam.questionList(this.questionParams).then(res => {
        const { status, data, message } = res.data
        if (status === 0) {
          this.title = data.title
          this.durationTime = formatTimes.formatTimestamp(data.durationTime)
          this.questionList.push(...data.list)
          this.questionParams.total = data.count
          if (this.questionParams.recordSize > 0) {
            this.$nextTick(() => {
              // 跳转到下一页第一个
              this.$refs.swipe.swipeTo(this.questionParams.recordSize - 1, { immediate: true })
            })
          }
          this.setTypeDivide()
        } else {
          this.$toast(message)
        }
      })
    },
    // 切换题目
    handleSwipeChange(index) {
      if (
        index === this.questionList.length - 1 &&
        Math.ceil(this.questionParams.total / this.questionParams.pageSize) !== this.questionParams.pageNumber
      ) {
        this.questionParams.pageNumber++
        this.getQuestionList()
      }
    },
    // 题目按类型区分
    setTypeDivide() {
      this.typeData.numberKeys = []
      this.typeData.number = {}
      for (let i = 0; i < this.questionList.length; i++) {
        const TypeDivideFlag = this.clacType(this.questionList[i], i)
        if (TypeDivideFlag) {
          this.typeData.number[i] = this.typeData.numberOptions[this.typeData.numberKeys.length]
          this.typeData.numberKeys.push(i)
        }
      }
    },
    // 答题卡切换到题目
    handleAnswerSheetClick(index) {
      this.curPage = 'question'
      this.$refs.swipe.swipeTo(index, { immediate: true })
    },
    // 多选题答案
    multipleChoose(item, optionItem) {
      if (item.myAnswer) {
        if (item.myAnswer.includes(optionItem.itemName)) {
          const index = item.myAnswer.findIndex(o => o === optionItem.itemName)
          if (index > -1) item.myAnswer.splice(index, 1)
        } else {
          item.myAnswer.push(optionItem.itemName)
        }
      } else {
        item.myAnswer = [optionItem.itemName]
      }
      const answerOptions = item.option.filter(o => item.myAnswer.includes(o.itemName))
      item.answer = answerOptions.map(o => o.itemName).join('')
    },
    // 答卷参数
    setAnswerParams() {
      const filterData = this.questionList.filter(o => o.answer)
      this.answerParams = filterData.map(o => {
        return {
          questionCode: o.code,
          answer: o.answer,
          version: o.version
        }
      })
    },
    // 超时提交答卷
    onFinish() {
      this.setAnswerParams()
      this.$dialog
        .alert({
          message: '答题时间已到，请交卷'
        })
        .then(() => {
          this.onSave()
        })
    },
    // 手动提交答卷
    onSubmit() {
      this.setAnswerParams()
      const unfinishedFlag = this.answerParams.findIndex(o => !o.answer)
      this.$dialog
        .confirm({
          title: '提示',
          message: `${unfinishedFlag > -1 ? '您还有未做完的试题，' : ''}是否确认交卷？`,
          confirmButtonText: '是',
          cancelButtonText: '否'
        })
        .then(() => {
          this.onSave()
        })
    },
    // 保存
    onSave() {
      LearnTest.Exam.save({
        examCode: this.$route.query.code,
        list: this.answerParams
      }).then(res => {
        const { status, message } = res.data
        if (status === 0) {
          this.$router.push('/page/message?backTo=-2&title=提交成功')
        } else {
          this.$toast.fail(message)
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
@import '~@/assets/style/learnTest/exam/question.less';
</style>
